﻿using System.Text.RegularExpressions;

namespace Guan.CMS.Model.Extension
{
    public static class ContentExtensions
    {
        /// <summary>
        /// 转换纯文本内容为 HTML 内容
        /// </summary>
        /// <param name="text">纯文本内容</param>
        /// <returns>转换后的 HTML 内容</returns>
        public static string TextToHtml(this string text)
        {
            return Regex.Replace(Regex.Replace(Regex.Replace(Regex.Replace(Regex.Replace("<p>" + text + "</p>", "\r\n", "</p><p>"), "\r", "</p><p>"), "\n", "<br />"), "\t", "    "), "  ", "  ");
        }
        /// <summary>
        /// 转换 Html 内容为纯文本内容
        /// </summary>
        /// <param name="html">HTML 内容</param>
        /// <returns>转换后的纯文本内容</returns>
        public static string HtmlToText(this string html)
        {
            string input = html;
            return Regex.Replace(Regex.Replace(Regex.Replace(Regex.Replace(Regex.Replace(Regex.Replace(input, @"(?m)<script[^>]*>(\w|\W)*?</script[^>]*>", "", RegexOptions.Multiline | RegexOptions.IgnoreCase), @"(?m)<style[^>]*>(\w|\W)*?</style[^>]*>", "", RegexOptions.Multiline | RegexOptions.IgnoreCase), @"(?m)<select[^>]*>(\w|\W)*?</select[^>]*>", "", RegexOptions.Multiline | RegexOptions.IgnoreCase), @"(?m)<a[^>]*>(\w|\W)*?</a[^>]*>", "", RegexOptions.Multiline | RegexOptions.IgnoreCase), "(<[^>]+?>)| ", "", RegexOptions.Multiline | RegexOptions.IgnoreCase), @"(\s)+", "", RegexOptions.Multiline | RegexOptions.IgnoreCase);
        }

        /// <summary>
        /// 获取第一张图片
        /// </summary>
        /// <param name="htmlText"></param>
        /// <returns></returns>
        public static string GetFirstImages(this string htmlText)
        {
            const string pattern = "<img [^~]*?>";
            const string pattern1 = "src\\s*=\\s*((\"|\')?)(?<url>\\S+)(\"|\')?[^>]*";
            string s = null;
            Match match = Regex.Match(htmlText, pattern, RegexOptions.IgnoreCase);  //找到img标记  
            if (match.Success)
            {
                string img = match.Value;
                string imgsrc = Regex.Match(img, pattern1, RegexOptions.IgnoreCase).Result("${url}");
                imgsrc = Regex.Replace(imgsrc, "\"|\'|\\>", "", RegexOptions.IgnoreCase);
                s = imgsrc;
            }
            return s;
        }
        
        /// <summary>
        /// 截取字符串
        /// </summary>
        /// <param name="text">待截取字符串</param>
        /// <param name="length">截取长度</param>
        /// <param name="suffix">后缀</param>
        /// <returns></returns>
        public static string CutString(this string text, int length, string suffix="...")
        {
            if (text.Length>length)
            {
                return text.Substring(0, length) + suffix;
            }
            return text;
        }
    }
}